package com.shxc.smarttrade.index.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.activity.AlphaActivity;
import com.shxc.smarttrade.account.activity.HelpCenterActivity;
import com.shxc.smarttrade.base.BaseFragment;
import com.shxc.smarttrade.currency.activity.WebActivity;
import com.shxc.smarttrade.index.activity.MessageCenterActivity;
import com.shxc.smarttrade.index.adapter.IndexNewsAdapter;
import com.shxc.smarttrade.index.model.BannerModel;
import com.shxc.smarttrade.index.model.EAInfoModel;
import com.shxc.smarttrade.index.model.MessageHavingModel;
import com.shxc.smarttrade.index.model.ShowImportanceArticleModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyHttpUtils;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.ToastUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.xchris.http.ViseHttp;
import org.xchris.http.callback.ACallback;
import org.xchris.http.mode.CacheMode;
import org.xchris.http.mode.CacheResult;
import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;
import org.xchris.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 */
@ContentView(R.layout.fragment_index)
public class IndexFragment extends BaseFragment {

    @ViewInject(R.id.message_red_imageview)
    ImageView message_red_imageview;
    @ViewInject(R.id.mzbannerview)
    MZBannerView mzbannerview;
    @ViewInject(R.id.linearlayout)
    LinearLayout linearlayout;
    @ViewInject(R.id.precision_rate_textview)
    TextView precision_rate_textview;
    @ViewInject(R.id.day_trad_textview)
    TextView day_trad_textview;
    @ViewInject(R.id.seven_profit_textview)
    TextView seven_profit_textview;
    @ViewInject(R.id.total_profit_textview)
    TextView total_profit_textview;
    @ViewInject(R.id.ch_name_textview)
    TextView ch_name_textview;
    @ViewInject(R.id.en_name_textview)
    TextView en_name_textview;
    @ViewInject(R.id.buy_status_textview)
    TextView buy_status_textview;
    @ViewInject(R.id.buy_valume_textview)
    TextView buy_valume_textview;
    @ViewInject(R.id.listview)
    ListView listview;

    private IndexNewsAdapter adapter;
    private List<ShowImportanceArticleModel.DataBean> list;

    private int eaId;
    private int selected = 0;
    private BannerModel bannerModel;

    private String banner_a = "file:///android_asset/banner/banner_a.png";
    private String banner_b = "file:///android_asset/banner/banner_b.png";
    private String banner_c = "file:///android_asset/banner/banner_c.png";

    @Event({R.id.customerservice_imageview, R.id.message_imageview, R.id.ea_view})
    private void onClick(View view) {

        switch (view.getId()) {
            case R.id.customerservice_imageview:
                //客服中心
                JumpTo(HelpCenterActivity.class);
                break;
            case R.id.message_imageview:
                //消息中心
                JumpTo(MessageCenterActivity.class);//新
//                JumpTo(MessageActivity.class);//旧
                break;
            case R.id.ea_view:
                //EA详情
                Intent intent = new Intent(getActivity(), AlphaActivity.class);
                if (eaId == -1) {
                    ToastUtils.showToast("数据错误");
                    return;
                }
                intent.putExtra("eaId", eaId);
                startActivity(intent);
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //新闻点击事件
                    ShowImportanceArticleModel.DataBean siam = (ShowImportanceArticleModel.DataBean) msg.obj;
                    Intent intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra("title", "资讯详情");
                    intent.putExtra("url", Contents.H5PLUS + siam.getId());
                    startActivity(intent);
                    break;
                case 1:
                    //ea详情
                    EAInfoModel eaInfoModel = (EAInfoModel) msg.obj;
                    eaId = eaInfoModel.getData().get(0).getId();
                    precision_rate_textview.setText(BaseUtils.getDigitsData(eaInfoModel.getData().get(0).getPrecisionRate(), 2) + "%");
                    day_trad_textview.setText(eaInfoModel.getData().get(0).getDayCount() + "笔");
                    seven_profit_textview.setText(BaseUtils.getDigitsData(eaInfoModel.getData().get(0).getWeekYieldRate(), 2) + "%");
                    total_profit_textview.setText(BaseUtils.getDigitsData(eaInfoModel.getData().get(0).getProfitRateCount(), 2) + "%");
                    ch_name_textview.setText(eaInfoModel.getData().get(0).getNewOpen().getSymbolCn());
                    en_name_textview.setText(eaInfoModel.getData().get(0).getNewOpen().getSymbolEn());

                    if (eaInfoModel.getData().get(0).getNewOpen().getCmd() == 0) {
                        buy_status_textview.setText("涨");
                        buy_status_textview.setBackground(getResources().getDrawable(R.drawable.bg_round_orange));
                    } else {
                        buy_status_textview.setText("跌");
                        buy_status_textview.setBackground(getResources().getDrawable(R.drawable.bg_round_green));
                    }
                    buy_valume_textview.setText(eaInfoModel.getData().get(0).getNewOpen().getVolume() + "手");
                    break;
                case 3:
                    //banner载入
                    switch (bannerModel.getData().size()){
                        case 0:
                            BannerModel.DataBean bda = new BannerModel.DataBean();
                            bda.setType(0);
                            bda.setImageName(banner_a);
                            bannerModel.getData().add(bda);
                        case 1:
                            BannerModel.DataBean bdb = new BannerModel.DataBean();
                            bdb.setType(0);
                            bdb.setImageName(banner_b);
                            bannerModel.getData().add(bdb);
                        case 2:
                            BannerModel.DataBean bdc = new BannerModel.DataBean();
                            bdc.setType(0);
                            bdc.setImageName(banner_c);
                            bannerModel.getData().add(bdc);
                            break;
                        default:
                            break;
                    }

                    List<String> bannerList = new ArrayList<>();
                    for (int i = 0; i < bannerModel.getData().size(); i++) {
                        bannerList.add(bannerModel.getData().get(i).getImageName());
                        Loger.e("------url", bannerModel.getData().get(i).getImageName());
                    }

                    initDots(bannerList.size());
                    mzbannerview.setPages(bannerList, new MZHolderCreator<BannerPaddingViewHolder>() {
                        @Override
                        public BannerPaddingViewHolder createViewHolder() {
                            return new BannerPaddingViewHolder();
                        }
                    });
                    changeDotStatus();
                    mzbannerview.pause();
                    mzbannerview.start();
                    break;
                case 4:
                    //banner载入失败
                    Loger.e("banner载入失败", "error");
                    bannerModel = new BannerModel();
                    bannerModel.setData(new ArrayList<BannerModel.DataBean>());
                    handler.sendEmptyMessage(3);

                    break;
                case 5:
                    MessageHavingModel messageHavingModel = (MessageHavingModel) msg.obj;
                    if (messageHavingModel.getErr_code().equals("0")) {
                        if (messageHavingModel.getData().isHaveMsg()) {
                            message_red_imageview.setVisibility(View.VISIBLE);
                        } else {
                            message_red_imageview.setVisibility(View.GONE);
                        }
                    }
                    break;
                case 6:
                    //banner的点击事件
                    int position = (int) msg.obj;
                    BannerModel.DataBean model = bannerModel.getData().get(position);
                    switch (model.getType()) {
                        case 1:
                            //1跳转到h5
                            Loger.e("htmlUrl", model.getLike());
                            Intent intent2 = new Intent(getActivity(), WebActivity.class);
                            intent2.putExtra("title", model.getName());
                            intent2.putExtra("url", model.getLike());
                            startActivity(intent2);
                            break;
                        case 2:
                            //2显示pageName的图片
                            Loger.e("imageUrl", model.getPageName());
                            Intent intent3 = new Intent(getActivity(), WebActivity.class);
                            intent3.putExtra("title", model.getName());
                            intent3.putExtra("url", model.getPageName());
                            startActivity(intent3);
                            break;
                        default:
                            // 0 什么都不做
                            break;
                    }
                    break;
            }
            super.dispatchMessage(msg);
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list = new ArrayList<>();
        adapter = new IndexNewsAdapter(mContext, list, handler);
        listview.setAdapter(adapter);
        initView();
    }

    private void initView() {
        //nanner
        mzbannerview.setIndicatorRes(R.color.colorAccent, R.color.colorPrimary);
        mzbannerview.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                selected = position;
                changeDotStatus();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        showbanner();
        eainfo();
        msghavemsg();
        showImportanceArticleList();
        mzbannerview.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        mzbannerview.pause();
    }

    /**
     * 初始化dot
     */
    private void initDots(int size) {
        linearlayout.removeAllViews();
        for (int i = 0; i < size; i++) {
            View view = new View(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 10);
            params.setMargins(8, 0, 8, 0);
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.dot_selector);
            linearlayout.addView(view);
        }
    }

    /**
     * 动态修改指示器的状态
     */
    private void changeDotStatus() {
        for (int i = 0; i < linearlayout.getChildCount(); i++) {
            linearlayout.getChildAt(i).setEnabled(i == selected);
        }
    }

    /**
     * 绑定banner图
     */
    public class BannerPaddingViewHolder implements MZViewHolder<String> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item_padding, null);
            mImageView = (ImageView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, final int position, String data) {
            // 数据绑定
            glideUtils.showImage(data, mImageView, R.mipmap.banner_error, R.mipmap.banner_error);
            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Message msg = new Message();
                    msg.what = 6;
                    msg.obj = position;
                    handler.sendMessage(msg);
                }
            });
        }
    }

    //首页轮播图
    private void showbanner() {
        Map param = MyHttpUtils.getParm(x.app(), null);
        ViseHttp.GET(Contents.SHOWBANNER)
                .params(param)
                .setLocalCache(true)
                .cacheMode(CacheMode.FIRST_REMOTE)
                .request(new ACallback<CacheResult<BannerModel>>() {
                    @Override
                    public void onSuccess(CacheResult<BannerModel> cacheResult) {//回调解析用的实体类
                        if (cacheResult == null || cacheResult.getCacheData() == null) {
                            Loger.e("SHOWBANNER", "null");
                            return;
                        }
                        Loger.e("SHOWBANNER", "success");
                        bannerModel = null;
                        bannerModel = cacheResult.getCacheData();
                        Gson gson = new Gson();
                        Loger.e("json",gson.toJson(bannerModel));
                        if (bannerModel.getData().size()==0) {
                            handler.sendEmptyMessage(4);
                        }else{
                            Message msg = new Message();
                            msg.what = 3;
                            handler.sendMessage(msg);
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Loger.e("e", "request errorCode:" + errCode + ",errorMsg:" + errMsg);
                        handler.sendEmptyMessage(4);
                    }
                });
    }

    //是否还有未读消息
    private void msghavemsg() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", SpUtils.getInt(getActivity(), "userId", -1) + "");
        map.put("accessToken", SpUtils.getString(getActivity(), "accessToken", ""));
        Map param = MyHttpUtils.getParm(x.app(),map);

        ViseHttp.GET(Contents.MSG_HAVEMSG)
                .params(param)
                .setLocalCache(true)
                .cacheMode(CacheMode.ONLY_REMOTE)
                .request(new ACallback<CacheResult<MessageHavingModel>>() {
                    @Override
                    public void onSuccess(CacheResult<MessageHavingModel> cacheResult) {
                        if (cacheResult == null || cacheResult.getCacheData() == null) {
                            Loger.e("MSG_HAVEMSG", "null");
                            return;
                        }
                        Loger.e("MSG_HAVEMSG", "success");
                        MessageHavingModel model = cacheResult.getCacheData();
                        Message msg = new Message();
                        msg.what = 5;
                        msg.obj = model;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Loger.e("Fail", errMsg);
                    }
                });
    }

    //EA详情
    private void eainfo() {
        Map<String, String> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getActivity(), "accessToken", ""));
        Map param = MyHttpUtils.getParm(x.app(),map);

        ViseHttp.GET(Contents.EAINFO)
                .params(param)
                .setLocalCache(true)
                .cacheMode(CacheMode.ONLY_REMOTE)
                .request(new ACallback<CacheResult<EAInfoModel>>() {
                    @Override
                    public void onSuccess(CacheResult<EAInfoModel> cacheResult) {
                        if (cacheResult == null || cacheResult.getCacheData() == null) {
                            Loger.e("EAINFO", "null");
                            return;
                        }
                        Loger.e("EAINFO", "success");
                        EAInfoModel model = cacheResult.getCacheData();
                        Loger.e("code",model.getErr_code());
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = model;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Loger.e("Fail", errMsg);
                    }
                });
    }

    //资讯展示
    private void showImportanceArticleList() {

        ViseHttp.GET(Contents.ARTICLE_SHOWIMPORTANCEARTICLELIST)
                .setLocalCache(true)
                .cacheMode(CacheMode.ONLY_REMOTE)
                .request(new ACallback<CacheResult<ShowImportanceArticleModel>>() {
                    @Override
                    public void onSuccess(CacheResult<ShowImportanceArticleModel> cacheResult) {
                        if (cacheResult == null || cacheResult.getCacheData() == null) {
                            Loger.e("ARTICLE_SHOWIMPORTANCEARTICLELIST", "null");
                            return;
                        }
                        Loger.e("ARTICLE_SHOWIMPORTANCEARTICLELIST", "success");
                        ShowImportanceArticleModel model = cacheResult.getCacheData();
                        if (model.getErr_code().equals("0")) {
                            adapter.upDate(model.getData());
                        }else{
                            Loger.e(model.getErr_code(),model.getErr_msg());
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Loger.e("Fail", errMsg);
                    }
                });
    }

    public void JumpTo(Class cla) {
        Intent intent = new Intent(getActivity(), cla);
        startActivity(intent);
    }

}
